import React, { useState, useEffect } from 'react';
import { Modal, View, TouchableOpacity, StyleSheet, ScrollView } from 'react-native';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import { WebView } from 'react-native-webview';
import { useReactive } from 'ahooks';
import { Text } from 'native-base';
import { CommonStyle } from '../common/commonStyle.ts';

interface IPickerProps {
  visible: boolean;
  data: Array<{ text: string; value: number | string }> | Array<Array<{ text: string; value: number | string }>>;
  selected?: Array<string | number>;
  onChange: () => void; // 变化事件
  onConfirm: (result: { names: string; values: Array<string | number> }) => void; // 确认事件
  onCancel: () => void; // 取消事件
  title?: string; // 可选标题
  closeOnClickOverlay?: boolean; // 是否在点击遮罩层后关闭
}

interface IState {
  uri: string;
  result: { names: string; values: Array<string | number> };
}
const Picker: React.FC<IPickerProps> = ({ visible, data, selected, onChange, onConfirm, onCancel, closeOnClickOverlay, title = '选择' }) => {
  const state = useReactive<IState>({
    uri: 'https://kics.kanglailab.com/picker',
    result: { names: '', values: [] },
  });

  useEffect(() => {
    if (visible) state.uri = `https://kics.kanglailab.com/picker?columns=${JSON.stringify(data)}&selected=${JSON.stringify(selected || [])}`;
  }, [visible]);

  /**
   * 处理来自 WebView 的消息
   * @param event
   */
  const handleWebViewMessage = async (event: any) => {
    const message: Array<{ text: string; value: number | string }> = JSON.parse(event.nativeEvent.data);
    state.result = {
      names: message
        .map((item) => item.text)
        .toString()
        .replace(/,/g, '-'),
      values: message.map((item) => item.value),
    };
  };

  /**
   * 提交
   */
  const handleConfirm = () => {
    if (onConfirm) onConfirm(state.result);
  };

  return (
    <Modal visible={visible} transparent animationType="fade">
      <View style={styles.container}>
        <Touchable
          style={styles.touchArea}
          onPress={() => {
            closeOnClickOverlay ? onCancel() : undefined;
          }}
        >
          <View></View>
        </Touchable>
        <View style={styles.container}>
          <View style={styles.pickerContainer}>
            {/* 标题和按钮 */}
            <View style={styles.header}>
              <TouchableOpacity onPress={onCancel}>
                <Text style={[styles.button, { color: '#969799' }]}>取消</Text>
              </TouchableOpacity>
              <Text style={styles.title}>{title}</Text>
              <TouchableOpacity onPress={handleConfirm}>
                <Text style={styles.button} color={CommonStyle.mainColor}>
                  确认
                </Text>
              </TouchableOpacity>
            </View>

            <View style={styles.pickerContent}>
              <WebView style={{ width: '100%', height: '100%' }} source={{ uri: state.uri }} onMessage={handleWebViewMessage} />
            </View>
          </View>
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.2)' },
  touchArea: { flex: 1, backgroundColor: 'rgba(0,0,0,0.2)' },
  header: { flexDirection: 'row', justifyContent: 'space-between', padding: 15, borderBottomWidth: 1, borderBottomColor: '#ddd' },
  title: { fontSize: 16, fontWeight: 'bold' },
  button: { fontSize: 14 },
  pickerContent: { position: 'relative', height: 300, justifyContent: 'center', paddingHorizontal: 16 },
  pickerContainer: { backgroundColor: '#fff', borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingBottom: 20 },
});

export default Picker;
